<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { NModal, NForm, NFormItem, NInput, NRadioGroup, NRadio, NSpace, useMessage } from 'naive-ui'
import type { FormInst, FormRules } from 'naive-ui'
import type { PermissionItemType } from '@/types/api/permission'
import { PERMISSION_DICT } from '@/constants/biz'
import { createPermissionApi, updatePermissionApi } from '@/api/permission'

const message = useMessage()

type PropsType = {
  id: string
  record: PermissionItemType | null
  onOk?: Function
}
const props = defineProps<PropsType>()
const title = computed(() => (props.record ? '编辑' : '新增'))
const showModal = ref(false)

const formRef = ref<FormInst | null>(null)
const formValue = ref<Omit<PermissionItemType, 'id' | 'children' | 'sort'> & { sort: string }>({
  permissionName: '',
  type: 'menu',
  permissionCode: '',
  path: '',
  sort: '10'
})
const formRules = computed<FormRules>(() => ({
  permissionName: {
    required: true,
    message: '请输入权限名称',
    trigger: ['input']
  },
  permissionCode: {
    required: formValue.value.type === 'button',
    message: '请输入权限码',
    trigger: ['input']
  },
  sort: {
    required: true,
    message: '请输入优先级',
    trigger: ['input']
  }
}))

watch(showModal, (val) => {
  if (val) {
    if (props.record) {
      const { permissionName, type, permissionCode, path, sort } = props.record
      formValue.value.permissionName = permissionName
      formValue.value.type = type
      formValue.value.permissionCode = permissionCode
      formValue.value.path = path
      formValue.value.sort = sort.toString()
    } else {
      formValue.value.permissionName = ''
      formValue.value.type = 'menu'
      formValue.value.permissionCode = ''
      formValue.value.path = ''
      formValue.value.sort = ''
    }
  } else {
    hasChanged.value = false
  }
})

// 表单是否改变过，如果没变过，确认操作也直接关闭弹窗
const hasChanged = ref(false)
const handleFormChange = () => {
  hasChanged.value = true
}

const handleOk = async () => {
  const { onOk, record, id } = props
  if (record && !hasChanged.value) {
    return (showModal.value = false)
  }
  await formRef.value?.validate()
  const { permissionName, type, permissionCode, sort, path } = formValue.value

  if (record) {
    // 编辑
    const payload = {
      id,
      permissionName,
      type,
      permissionCode: type === 'button' ? permissionCode : '',
      path: type === 'menu' ? path : '',
      sort: parseInt(sort)
    }
    await updatePermissionApi(payload)
  } else {
    // 新增
    const payload = {
      parentId: id,
      permissionName,
      type,
      permissionCode: type === 'button' ? permissionCode : '',
      path: type === 'menu' ? path : '',
      sort: parseInt(sort)
    }
    await createPermissionApi(payload)
  }
  message.success(`${title.value}成功`)
  showModal.value = false
  onOk && onOk()
}

defineExpose({
  showModal
})
</script>

<template>
  <NModal
    v-model:show="showModal"
    :title="title"
    preset="dialog"
    positive-text="确认"
    negative-text="取消"
    to=".permission-container"
    @positiveClick="handleOk"
  >
    <div style="margin-top: 20px">
      <NForm ref="formRef" :model="formValue" :rules="formRules" :onchange="handleFormChange">
        <NFormItem label="权限名称" path="permissionName">
          <NInput
            v-model:value="formValue.permissionName"
            placeholder="请输入权限名称"
            :clearable="true"
          />
        </NFormItem>
        <NFormItem label="权限类型" path="type">
          <NRadioGroup v-model:value="formValue.type" :disabled="!!props.record">
            <NSpace>
              <NRadio v-for="(v, k) of PERMISSION_DICT" :key="k" :value="k">{{ v }}</NRadio>
            </NSpace>
          </NRadioGroup>
        </NFormItem>
        <template v-if="formValue.type === 'menu'">
          <NFormItem label="菜单路径" path="path">
            <NInput v-model:value="formValue.path" placeholder="请输入菜单路径" :clearable="true" />
          </NFormItem>
        </template>
        <template v-else>
          <NFormItem label="权限码" path="permissionCode">
            <NInput
              v-model:value="formValue.permissionCode"
              placeholder="请输入权限码"
              :clearable="true"
            />
          </NFormItem>
        </template>
        <NFormItem label="优先级(越小越靠前)" path="sort">
          <NInput v-model:value="formValue.sort" placeholder="请输入优先级" :clearable="true" />
        </NFormItem>
      </NForm>
    </div>
  </NModal>
</template>

<style lang="scss" scoped></style>
